package com.huanzhidadi.single.compare;

import lombok.Data;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/**
 * 自定义比较器
 * 可以按照多个条件进行比较，String类型用compareTo进行比较
 */
public class TreeSetSortTest {

    public static void main(String[] args) {
        List<Person> list = createData();
        System.out.println("排序前");
        list.stream().forEach(System.out::println);

        TreeSet<Person> t1 = new TreeSet<>((l, r) -> l.getId() < r.getId() ? 1 : -1);
        t1.addAll(list);
        System.out.println("按照id进行降序排列");
        t1.stream().forEach(System.out::println);

        TreeSet<Person> t2 = new TreeSet<>((l, r) ->
                l.getScore() != r.getScore()
                        ? (l.getScore() > r.getScore() ? -1 : 1)
                        : (l.getId() > r.getId() ? 1 : -1));
        t2.addAll(list);
        System.out.println("按照score进行降序排序，如果成绩一样，按照id进行升序排列");
        t2.stream().forEach(System.out::println);
    }

    public static List<Person> createData() {
        List<Person> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Person p = new Person();
            p.setId(i);
            p.setName("抡砖" + i + "号");
            p.setScore(107 - i);

            list.add(p);
        }

        for (int i = 10; i >= 5; i--) {
            Person p = new Person();
            p.setId(20 - i);
            p.setName("抡砖" + (i) + "号");
            p.setScore(100 + i);

            list.add(p);
        }

        return list;
    }
}

@Data
@ToString
class Person {
    private String name;
    private int id;
    private int score;
}